<?php

/**
 * 每天汇总数据
 *
 * @author mengyu wang
 */

require_once 'CommonController.php';

class Admin_DayDataController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_DayDataPlus();
        $this->_ddModel = new Application_Model_DayData();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function indexAction()
    {
        $time = time();
        $cookieModel = new Application_Model_Cookie();

        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['osName'] = trim($this->_request->get('osName'));
        $vars['sourceId'] = trim($this->_request->get('sourceId'));
        $vars['sourceSubId'] = trim($this->_request->get('sourceSubId'));
        $vars['startTime'] = trim($this->_request->get('startTime'));
        $vars['endTime'] = trim($this->_request->get('endTime'));
        $urls = $vars;

        $wheres[] = "`productCode` = '". Application_Model_UserLogin::getInstance()->getUserCurrentProductCode() ."'";
        if ($vars['osName'] != '') {
            $wheres[] = "`osName` = '" . addslashes($vars['osName']) . "'";
        }
        if ($vars['sourceId'] != '') {
            $wheres[] = "`sourceId` = '" . addslashes($vars['sourceId']) . "'";
        }
        if ($vars['sourceSubId'] != '') {
            $wheres[] = "`sourceSubId` = '" . addslashes($vars['sourceSubId']) . "'";
        }
        if ($vars['startTime'] != '') {
            $wheres[] = "`date` >= '{$vars['startTime']}' ";
        }
        if ($vars['endTime'] != '') {
            $wheres[] = "`date` <= '{$vars['endTime']}' ";
        }

        $orderBy = "`addTime` DESC, `id` DESC";

        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT * FROM `{$this->_model->getTableName()}`
        {$where}
        ORDER BY {$orderBy}";

        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        $rows = $dbPaginator->getRows();

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
		$_SESSION['where'] = $where;  //存储查询条件
    }
    
     /**
     * 导出动作
     * @author genjie.wang
     * @return void
     */
    public function outputAction(){
        $this->view->baseUrl = $this->_configs['project']['baseUrl'];
        $sql = "SELECT * FROM `{$this->_model->getTableName()}`
        ".$_SESSION['where'];
        //获取当前页码
        $pageSize = 500;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
            $start = 0;
            $if = fopen('./data/'.$this->_currentUserRow['userName'].'.csv', 'w');
            $title = "日期 , 操作系统,Source,SourceSub,装机数,装机IP数,启动次数,启动客户端数,总订单数,有效订单数,总订单金额,有效订单金额,\n";
            $title = iconv( "UTF-8", "gb2312//IGNORE", $title);
            fwrite($if, $title);
        }else {
            $if = fopen('./data/'.$this->_currentUserRow['userName'].'.csv', 'a');
             $start= $pageNo * $pageSize;
        }
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();
        
        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $rows = $dbPaginator->getRows();
        $val = "";
        $i = 0;
        
        foreach( $rows as $key => $value ) {
            $val .= $value['date'] . ',';
            $val .= $value['osName'] . ',';
            $val .= $value['sourceId'] . ',';
            $val .= $value['sourceSubId'] . ',';
            $val .= $value['installNum'] . ',';
            $val .= $value['installIpNum'] . ',';
            $val .= $value['bootNum'] . ',';
            $val .= $value['bootClientNum'] . ',';
            $val .= $value['orderNum'] . ',';
            $val .= $value['okOrderNum'] . ',';
            $val .= $value['orderAmount'] . ',';
            $val .= $value['okOrderAmount'] . ',';
            $val .= "\n"; 
            $i++;
        }
        
        fwrite($if, $val);
        fclose($if);
		//$this->name = $this->_currentUserRow;
        if ( ($recordCount + 500) > ($pageSize * $pageNo + $i) ){
            echo "共{$recordCount}条，每组导出{$pageSize}条，第{$pageNo}组处理完毕，正在准备处理下一组...<script>setTimeout(function(){location.href='?&pageNo=". ($pageNo + 1) ."';}, 1000);</script>";
            exit;
        }else {
            //文件生成功，模板中输出下载
        }
    }
    
    /**
     * 日运营报表-日
     */
    public function dayMemberType($startTime)
    {               
        $this->view->title = '运营报表';
        $this->view->reportType = 'op-report';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->isDay = 1;
        $this->view->startTime = $startTime;
        $this->view->endTime = $startTime;
        $totals = $this->view->totals = $this->_ddModel->getDayMemberType($startTime, $productCode);
        
        if (count($totals)!=0) { 
        for ($i=0; $i<count($totals); ++$i) {           
            foreach ($totals[$i] as $key=>$val) {
                if ($key != 'memberName') {
                    @$totalRow[$key]+=($val);
                } 
            }           
        }
        //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        $this->view->totals[$i] = $totalRow;
        $this->view->totals[$i]['memberName'] = '总计';
        }
    }

    /**
     * 日运营报表-时间段
     */
    public function dateMemberType($startTime, $endTime, $isAll=0)
    {
        $this->view->title = '运营报表';
        $this->view->reportType = 'op-report';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        if ($startTime) {
           $totals = $this->view->totals = $this->_ddModel->getDateMemberType($startTime, $endTime, $productCode);
        } else {
           $totals = $this->view->totals = $this->_ddModel->getAllMemberType($productCode);
        }
        
        $this->view->isDay = 0; 
        $this->view->startTime = $startTime;
        $this->view->endTime = $endTime;
        
      if (count($totals)!=0) { 
        for ($i=0; $i<count($totals); ++$i) {           
            foreach ($totals[$i] as $key=>$val) {
                if ($key != 'memberName') {
                    @$totalRow[$key]+=($val);
                } 
            }           
        }
        //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        $this->view->totals[$i] = $totalRow;
        $this->view->totals[$i]['memberName'] = '总计';
        }
    }
    
    /**
     * 获取广告渠道列表
     */
    public function expandAdMemberAction()
    {
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	if(!$startTime) {
    		//所有时间段的
    		$members = $this->_model->schedualMember('','',$productCode);
    	} else {
    		$members = $this->_model->schedualMember($startTime, $endTime, $productCode);
    	}
    	$members = $this->_model->formatNum($members);
    	$json_string = json_encode($members);
    	echo $json_string;
    	exit();
    }
    
    /**
     * 获取广告渠道的SOURCEID列表
     * @return JSON 
     */
    public function adMemberSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
        $rows = $this->_model->schedualMemberSourceId($startTime, $endTime, $productCode, $memberName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取广告渠道的SUBSOURCEID列表
     * @return JSON 
     */
    public function adMemberSubSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
    	$sourceId = $this->_request->get('sourceId');
        $rows = $this->_model->schedualMemberSourceIdSourceSubId($startTime, $endTime, $productCode, $memberName, $sourceId);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取其他渠道的列表
     * @return JSON 
     */
    public function expandFreeMemberAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
        $rows = $this->_model->noSchedualMember($startTime, $endTime, $productCode);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取其他渠道的SOURCEID列表
     * @return JSON 
     */
    public function freeMemberSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
        $rows = $this->_model->noSchedualMemberSourceId($startTime, $endTime, $productCode, $memberName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    
    /**
     * 获取其他渠道的SOURCEID-SUBSOURCEID列表
     * @return JSON 
     */
    public function freeMemberSubSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
    	$sourceId = $this->_request->get('sourceId');
        $rows = $this->_model->noSchedualMemberSourceIdSourceSubId($startTime, $endTime, $productCode, $memberName, $sourceId);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    

    
    /**
     * 运营日报总入口
     */
    public function opReportAction()
    {
        $day = $this->_request->get('day');
        if ($day == '' || $day == 'yestoday') {
            //默认为昨天
            $this->opReportYestoday();
        } else if ($day == 'last-seven-day') {
            $this->opReportLastSevenDay();
        } else if ($day == 'last-thirty-day') {
            $this->opReportLastThirtyDay();            
        } else if ($day == 'last-three-month') {
            $this->opReportLastThreeMonth();
        } else if($day == 'all') {
            $this->opReportAll();
        } else if ($day == 'between') {
            $this->opReportBetween();
        }
        $this->renderScript('day-data/day-member-type.php');

    }
    
    /**
     * 运营报表-昨天
     * Enter description here ...
     */
    public function opReportYestoday()
    {
        $this->view->key = 'yestoday';
        $startTime = date('Y-m-d',strtotime("-1 day"));
        $this->dayMemberType($startTime);       
    }    
    
    /**
     * 运营报表-最近七天
     * Enter description here ...
     */
    public function opReportLastSevenDay()
    {
        $this->view->key = 'last-seven-day';
        $startTime = date('Y-m-d',strtotime("-8 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->dateMemberType($startTime, $endTime);
    }
    
    /**
     * 运营报表-最近30天
     * Enter description here ...
     */
    public function opReportLastThirtyDay()
    {
        $this->view->key = 'last-thirty-day';
        $startTime = date('Y-m-d',strtotime("-31 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->dateMemberType($startTime, $endTime);
    }
    
    /**
     * 运营报表-最近3个月
     * Enter description here ...
     */
    public function opReportLastThreeMonth()
    {
        $this->view->key = 'last-three-month';
        $startTime = date('Y-m-d',strtotime("-3 months"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->dateMemberType($startTime, $endTime);
    }
    
    /**
     * 运营报表-全部
     * Enter description here ...
     */
    public function opReportAll()
    {
        $this->view->key = 'all';
        $this->view->isDay = 0;
        $this->dateMemberType('', '', 1);
    }
    
    /**
     * 运营报表-选择时间段
     * Enter description here ...
     */
    public function opReportBetween()
    {
        $this->view->key = 'between';
        $this->view->title = '运营报表';
        $this->view->reportType = 'op-report';
        if ($this->_request->isPost()) {
            $startTime = $this->_request->get('startTime');
            $endTime = $this->_request->get('endTime');
            $backUrl = $this->view->projectUrl(array('action' => $this->view->reportType,'day'=>'between'));
            if (!$startTime || !$endTime) {
                 echo $this->view->message('请选择时间范围！',$backUrl); exit;
            } else if($startTime>$endTime) {
                 echo $this->view->message('开始时间必须早于结束时间，请重新填写！', $backUrl); exit;  
            } else {
                $this->view->startTime = $startTime;
                $this->view->endTime = $endTime;
            }
            if ($startTime == $endTime) {
            	$this->dayMemberType($startTime);
            } else {
            	$this->dateMemberType($startTime, $endTime);
            }
        }
    }
    
    /**
     * 广告投放-日
     */
    public function dayAd($startTime)
    {        
        $this->view->title = '广告投放报表';
        $this->view->reportType = 'ad-report';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        //付费广告
        $totalRow = array();
        $rowsPaid = $this->_ddModel->getDayPaidAd($startTime, $productCode);
        $this->view->rowsPaid = $rowsPaid;
        
        if (count($rowsPaid)!=0) { 
        for ($i=0; $i<count($rowsPaid); ++$i) {           
            foreach ($rowsPaid[$i] as $key=>$val) {
                if ($key != 'name') {
                    @$totalRow[$key]+=($val);
                } 
            }           
        }
        //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        @$totalRow['ROI'] =  $totalRow['okOrderAmount']/$totalRow['adPrice'];
        $this->view->rowsPaid[$i] = $totalRow;
        $this->view->rowsPaid[$i]['name'] = '总计';
        }        
    }
    
    /**
     * 广告投放-时间段
     */
    public function dateAd($startTime, $endTime, $isAll=0)
    {        
        $this->view->title = '广告投放报表';
        $this->view->reportType = 'ad-report';
        $this->view->startTime = $startTime;
        $this->view->endTime = $endTime;                
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        //付费广告
        $totalRow = array();
        if ($isAll==1) {
            $rowsPaid = $this->_ddModel->getAllPaidAd($productCode);
        } else {
            $rowsPaid = $this->_ddModel->getDatePaidAd($startTime, $endTime, $productCode);
        }
       
        $this->view->rowsPaid = $rowsPaid;
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'name') {
                        @$totalRow[$key]+=($val);
                    } 
                }           
            }
            //客单价统计
        	@$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        	@$totalRow['ROI'] =  $totalRow['okOrderAmount']/$totalRow['adPrice'];
            $this->view->rowsPaid[$i] = $totalRow;               
            $this->view->rowsPaid[$i]['name'] = '总计';                    
        }                  
     }
     
    /**
     * 下载广告日报EXCEL
     */
    public function exportAdReportAction()
    {
    	//收集广告渠道的数据
        $filter = new Zend_Filter_StripTags();
        $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
        $endTime = $filter->filter(trim($this->_request->getPost('endTime')));              
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $day = $this->_request->get('day');
        if ($day == 'all') {
        	$isAll = 1;
        } else {
        	$isAll = 0;
        }
        if ($startTime && $endTime) {
        	if ($startTime != $endTime) {
        		$timeMessage = $startTime . '_' . $endTime;
        	} else {
        		$timeMessage = $startTime;
        	}
        } else {
        	$timeMessage = 'all_';
        }
        
        //付费广告
        $totalRow = array();
        if ($isAll==1) {
            $rowsPaid = $this->_ddModel->getAllPaidAd($productCode);
        } else {
            $rowsPaid = $this->_ddModel->getDatePaidAd($startTime, $endTime, $productCode);
        }
        
        if (count($rowsPaid)) {
            for ($i=0; $i<count($rowsPaid); ++$i) {           
                foreach ($rowsPaid[$i] as $key=>$val) {
                    if ($key != 'name') {
                        @$totalRow[$key]+=($val);
                    } 
                }           
            }
            //客单价统计
        	@$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        	@$totalRow['ROI'] =  $totalRow['okOrderAmount']/$totalRow['adPrice'];
        	$rowsPaid[$i]['name'] = '总计'; 
        	foreach ($totalRow as $key=>$val) {
        		$rowsPaid[$i][$key] = $val;
        	}
        }
        
        //将数据导出到EXCEL文件
        $ddModel = new Application_Model_DayData();
        $pModel = new Application_Model_PartnerProduct();
        $product = $pModel->fetchRow("code = '{$productCode}'");
        $keyAdPaidArr = array('广告渠道', 'ROI', '订单金额', '订单量', '客单价', '广告成本');
        $adPaidFile = $ddModel->writeToExcel('adPaid', $timeMessage, $rowsPaid,$productCode,$keyAdPaidArr,'广告投放');
        $path = PUBLIC_PATH . "/data/dayData/";
        $filename = $path . $adPaidFile;
        
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $adPaidFile);
		readfile($filename);
        
        //文件的删除
        @unlink($filename);
        exit();
    }
     
   /**
     * 获取广告投放渠道的SOURCEID列表
     * @return JSON 
     */
    public function adPutOnMemberSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
        $rows = $this->_model->putOnSchedualMemberSourceId($startTime, $endTime, $productCode, $memberName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取广告投放渠道的SUBSOURCEID列表
     * @return JSON 
     */
    public function adPutOnMemberSubSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
    	$sourceId = $this->_request->get('sourceId');
        $rows = $this->_model->putOnSchedualMemberSourceIdSourceSubId($startTime, $endTime, $productCode, $memberName, $sourceId);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
     
     /**
      * 广告投放 - 入口
      */
     public function adReportAction()
     {
        $day = $this->_request->get('day');
        if ($day == '' || $day == 'today') {
            //默认为今天
            $this->adReportToday();
        } else if ($day == 'yestoday') {
        	$this->adReportYestoday();
        } else if ($day == 'last-seven-day') {
            $this->adReportLastSevenDay();
        } else if ($day == 'last-thirty-day') {
            $this->adReportLastThirtyDay();            
        } else if ($day == 'last-three-month') {
            $this->adReportLastThreeMonth();
        } else if($day == 'all') {
            $this->adReportAll();
        } else if ($day == 'between') {
            $this->adReportBetween();
        }
        $this->renderScript('day-data/day-ad.php');
        
     }
     
     /**
     * 广告投放-昨天
     */
    public function adReportYestoday()
    {
        $this->view->key = 'yestoday';
        $this->view->endTime = $this->view->startTime = $startTime = date('Y-m-d',strtotime("-1 day"));
        $this->dayAd($startTime);       
    }
     /**
     * 广告投放-今天
     */
    public function adReportToday()
    {
        $this->view->key = 'today';
        $this->view->endTime = $this->view->startTime = $startTime = date('Y-m-d',strtotime("now"));
        $this->dayAd($startTime);       
    }
    
     /**
     * 广告投放-7天前
     */
    public function adReportLastSevenDay()
    {
        $this->view->key = 'last-seven-day';
        $startTime = date('Y-m-d',strtotime("-8 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));
        $this->dateAd($startTime, $endTime);
    }
    
     /**
     * 广告投放-30天前
     */
    public function adReportLastThirtyDay()
    {
        $this->view->key = 'last-thirty-day';
        $startTime = date('Y-m-d',strtotime("-31 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));
        $this->dateAd($startTime, $endTime);
    }
    
     /**
     * 广告投放-3个月前
     */
    public function adReportLastThreeMonth()
    {
        $this->view->key = 'last-three-month';
        $startTime = date('Y-m-d',strtotime("-3 months"));
        $endTime = date('Y-m-d',strtotime("-1 day"));
        $this->dateAd($startTime, $endTime);
    }
    
     /**
     * 广告投放-全部
     */
    public function adReportAll()
    {
        $this->view->key = 'all';
        $this->dateAd('', '', 1);
    }
    
    /**
     * 广告投放-选择时间段
     * Enter description here ...
     */
    public function adReportBetween()
    {
        $this->view->key = 'between';
        $this->view->title = '广告投放报表';
        $this->view->reportType = 'ad-report';
        if ($this->_request->isPost()) {
            $startTime = $this->_request->get('startTime');
            $endTime = $this->_request->get('endTime');
            $backUrl = $this->view->projectUrl(array('action' => $this->view->reportType,'day'=>'between'));
            if (!$startTime || !$endTime) {
                 echo $this->view->message('请选择时间范围！',$backUrl); exit;
            } else if($startTime>$endTime) {
                 echo $this->view->message('开始时间必须早于结束时间，请重新填写！', $backUrl); exit;  
            } else {
                $this->view->startTime = $startTime;
                $this->view->endTime = $endTime;
            }
            if ($startTime == $endTime) {
            	$this->dayAd($startTime);
            } else {
            	$this->dateAd($startTime, $endTime); 
            }
                
        }   
    }
        
    
    /**
     * 操作系统 - 日
     */
    public function dayOs($startTime)
    {
        $this->view->title = '操作系统报表';
        $this->view->reportType = 'os-report';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->isDay = 1;
        //日运营按操作系统统计报表
        $totalRow = array();
        $rows = $this->_ddModel->getDayOs($startTime, $productCode);
        $this->view->rows = $rows;
        
        if (count($rows)) {
            for ($i=0; $i<count($rows); ++$i) {           
                foreach ($rows[$i] as $key=>$val) {
                    if ($key != 'osName') {
                        @$totalRow[$key]+=($val);
                    } 
                }           
            }
            //客单价统计
        	@$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
            $this->view->rows[$i] = $totalRow;
            $this->view->rows[$i]['osName'] = '总计';
        }   
    }
    
    /**
     * 日运营按操作系统按时间段查询报表
     */
    public function dateOs($startTime, $endTime, $isAll=0)
    {
        $this->view->title = '操作系统报表'; 
        $this->view->reportType = 'os-report';   
        $this->view->isDay = 0;  
        $this->view->startTime = $startTime;
        $this->view->endTime = $endTime;  
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        //日运营按操作系统统计报表
        $totalRow = array();
        if ($isAll==1) {
            $rows = $this->_ddModel->getAllOs($productCode);
        } else {
            $rows = $this->_ddModel->getDateOs($startTime, $endTime, $productCode);
        }
        
        $this->view->rows = $rows;
        
        if (count($rows)) {
            for ($i=0; $i<count($rows); ++$i) {           
                foreach ($rows[$i] as $key=>$val) {
                    if ($key != 'osName') {
                        @$totalRow[$key]+=($val);
                    } 
                }           
            }
            //客单价统计
        	@$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
            $this->view->rows[$i] = $totalRow;
            $this->view->rows[$i]['osName'] = '总计';
        }
    }
    
    /**
     * 下载操作系统日报EXCEL
     */
    public function exportOsReportAction()
    {
    	//收集数据
        $filter = new Zend_Filter_StripTags();
        $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
        $endTime = $filter->filter(trim($this->_request->getPost('endTime')));              
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $day = $this->_request->get('day');
        if ($day == 'all') {
        	$isAll = 1;
        } else {
        	$isAll = 0;
        }
        if ($startTime && $endTime) {
        	if ($startTime != $endTime) {
        		$timeMessage = $startTime . '_' . $endTime;
        	} else {
        		$timeMessage = $startTime;
        	}
        } else {
        	$timeMessage = 'all_';
        }
        
        $totalRow = array();
        if ($isAll==1) {
            $rows = $this->_ddModel->getAllOs($productCode);
        } else {
            $rows = $this->_ddModel->getDateOs($startTime, $endTime, $productCode);
        }
        $totalRow['osName'] = '总计';
        if (count($rows)) {
            for ($i=0; $i<count($rows); ++$i) {           
                foreach ($rows[$i] as $key=>$val) {
                    if ($key != 'osName') {
                        @$totalRow[$key]+=($val);
                    } 
                }           
            }
        }
        //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        $rows[$i] = $totalRow;
        
        
        //将数据导出到EXCEL文件
        $ddModel = new Application_Model_DayData();
        $pModel = new Application_Model_PartnerProduct();
        $product = $pModel->fetchRow("code = '{$productCode}'");
        $keyOsArr = array('操作系统', '订单金额', '订单量', '客单价', '激活量', '激活用户提交订单量', '激活用户提交订金额');
        $adPaidFile = $ddModel->writeToExcel('os', $timeMessage, $rows,$productCode,$keyOsArr,'操作系统');
        $path = PUBLIC_PATH . "/data/dayData/";
        $filename = $path . $adPaidFile;
        
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $adPaidFile);
		readfile($filename);
        
        //文件的删除
        @unlink($filename);
        exit();
    }
    
    /**
     * 系统-入口
     */
    public function osReportAction()
    {
        $day = $this->_request->get('day');
        if ($day == '' || $day == 'today') {
            //默认为昨天
            $this->osReportToday();
        } else if ($day == 'yestoday') {
            $this->osReportYestoday();
        } else if ($day == 'last-seven-day') {
            $this->osReportLastSevenDay();
        } else if ($day == 'last-thirty-day') {
            $this->osReportLastThirtyDay();            
        } else if ($day == 'last-three-month') {
            $this->osReportLastThreeMonth();
        } else if($day == 'all') {
            $this->osReportAll();
        } else if ($day == 'between') {
            $this->osReportBetween();
        }
        $this->renderScript('day-data/day-os.php');
    }
    
     /**
     * 系统-昨天
     */
    public function osReportYestoday()
    {
        $this->view->key = 'yestoday';
        $this->view->startTime = $this->view->endTime = $startTime = date('Y-m-d',strtotime("-1 day"));
        $this->dayOs($startTime);
       
    }
     /**
     * 系统-今天
     */
    public function osReportToday()
    {
        $this->view->key = 'today';
        $this->view->startTime = $this->view->endTime = $startTime = date('Y-m-d',strtotime("now"));
        $this->dayOs($startTime);
       
    }
    
     /**
     * 系统-7天前
     */
    public function osReportLastSevenDay()
    {
        $this->view->key = 'last-seven-day';
        $startTime = date('Y-m-d',strtotime("-8 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));
        $this->dateOs($startTime, $endTime);
    }
    
     /**
     * 系统-30天前
     */
    public function osReportLastThirtyDay()
    {
        $this->view->key = 'last-thirty-day';
        $startTime = date('Y-m-d',strtotime("-31 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));
        $this->dateOs($startTime, $endTime);
    }
    
     /**
     * 系统-3个月前
     */
    public function osReportLastThreeMonth()
    {
        $this->view->key = 'last-three-month';
        $startTime = date('Y-m-d',strtotime("-3 months"));
        $endTime = date('Y-m-d',strtotime("-1 day"));
        $this->dateOs($startTime, $endTime);
    }
    
     /**
     * 系统-全部
     */
    public function osReportAll()
    {
        $this->view->key = 'all';
        $this->dateOs('', '', 1);        
    }
    
    /**
     * 系统-选择时间段
     * Enter description here ...
     */
    public function osReportBetween()
    {
        $this->view->key = 'between';
        $this->view->title = '操作系统报表';
        $this->view->reportType = 'os-report';
        if ($this->_request->isPost()) {
            $startTime = $this->_request->get('startTime');
            $endTime = $this->_request->get('endTime');
            $backUrl = $this->view->projectUrl(array('action' => $this->view->reportType,'day'=>'between'));
            if (!$startTime || !$endTime) {
                 echo $this->view->message('请选择时间范围！',$backUrl); exit;
            } else if($startTime>$endTime) {
                 echo $this->view->message('开始时间必须早于结束时间，请重新填写！', $backUrl); exit;  
            } else {
                $this->view->startTime = $startTime;
                $this->view->endTime = $endTime;
            }
            if ($startTime == $endTime) {
            	$this->dayOs($startTime);
            } else {
            	$this->dateOs($startTime, $endTime);
            }
             
        }   
    }  
    
    /**
     * 上个月的每日激活量和订单数据视图
     */
    public function monthInstallNumAction()
    {
        	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        	$startTime = strtotime("-27 days");
	        $endTime = strtotime("-1 day");
	        
	        //激活量数据
	        $series = array();
	        //广告渠道
	        $adInstallNum = array();
	        //免费渠道
	        $freeInstallNum = array();
	        $num = 0;
	        for ($i=$startTime; $i <= $endTime; $i = $i+24*60*60) {
	            $date = date('Y-m-d',$i);
	            ++$num;
	            $dayData = $this->_ddModel->getProductInstallNum($productCode,$date);
	            $adInstallNum[] = intval($dayData['adInstallNum']);
	            $freeInstallNum[] = intval($dayData['freeInstallNum']);
	            $currDay[] = date('Y-n-j',$i);
	        }
    	   
	        $series[] = array(
	        'name'=>'广告渠道',
	        'data'=>$adInstallNum
	        );
	        $this->view->adInstallNum = json_encode($adInstallNum);
	        
	        $adData = '';
	        foreach ($series[0]['data'] as $item) {
	            $adData .= intval($item).',';
	        }
	        $adData = substr($adData, 0, strlen($adData)-1);
	        $series[0]['data'] = $adData;
	        
	        $adData = '';
	        $series[] = array(
	        'name'=>'免费渠道',
	        'data'=>$freeInstallNum
	        );
	        $this->view->freeInstallNum = json_encode($freeInstallNum);
	        
//	     //获取最大的数量值的120%的整数
      		$maxNum = 0;
      		foreach ($adInstallNum as $val) {
      			if ($val > $maxNum) {
      				$maxNum = $val;
      			}
      		} 
          	foreach ($freeInstallNum as $val) {
      			if ($val > $maxNum) {
      				$maxNum = $val;
      			}
      		} 
      		$this->view->maxNum = intval(1.2*$maxNum);
      	
	        foreach ($series[1]['data'] as $item) {
	            $adData .= intval($item).',';
	        }
	        $adData = substr($adData, 0, strlen($adData)-1);
	        $series[1]['data'] = $adData;
	        $this->view->series = $series;
	        $product = $this->_productModel->fetchRow("code='{$productCode}'");
	        $this->view->productName = $product['name'];

	        $this->view->categories = $this->json_encode($currDay);
	        $this->view->timeDesc = '最近一个月'; 
	        
	        //订单数据
	        $series = array();
	        $okOrderAmount = array();
	        $okOrderNum = array();
	        $currDay = array();
	        for ($i=$startTime; $i<=$endTime; $i=$i+24*60*60) {
	        	
	            $date = date('Y-m-d',$i);
	            //订单每日汇总数据
	            $dayData = $this->_ddModel->getProductDayData($productCode,$date);
	            $okOrderAmount[] = floatval($dayData['okOrderAmount']);
	            $okOrderNum[] = intval($dayData['okOrderNum']);
	            $currDay[] = date('Y-n-j',$i);
	        }
	        
	        $series[] = array(
	        'name'=>'销售额',
	        'yAxis'=>1,
	        'type'=>'column',
	        'data'=>$okOrderAmount
	        );
	        $this->view->monthSales = $this->json_encode($okOrderAmount);
	       
	        $series[] = array(
	        'name'=>'订单数',
	        'type'=>'spline',
	        'data'=>$okOrderNum
	        ); 
	               
	        $this->view->monthOrderNum = $this->json_encode($okOrderNum);
	        $this->view->orderCategories = $this->json_encode($currDay);
	        $this->view->orderTimeDesc = '最近一个月'; 
	        $this->renderScript('day-data/month-install-num.php');
      }
      
      public function json_encode($row)
      {
      	$str = '';
      	if (is_array($row)) {
	      	foreach ($row as $key=>$val) {
	      		if (is_numeric($val)) {
	      			$str .= $val.', ';
	      		} else {
	      			$str .= "'" . $val ."', ";
	      		}
	      	}
	      	return substr($str, 0, strlen($str)-2);
      	}
      	
      }
}

